//获取cookie、
export function getCookie(name) {
    console.log(document.cookie);
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg))
        return (arr[2]);
    else
        return null;
}

//设置cookie,增加到vue实例方便全局调用
export function setCookie (c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
};

//删除cookie
export function delCookie (name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
};

// 时间转换方法
export function dateFrom(dataStr, form='y-m-d h:mm:s'){
    var time = new Date(dataStr);
	function timeAdd0(str) {
		if(str<10){
			str='0'+str;
		}
		return str
	}
	var y = time.getFullYear();
	var m = time.getMonth()+1;
	var d = time.getDate();
	var h = time.getHours();
	var mm = time.getMinutes();
    var s = time.getSeconds();
    if(form == 'y-m-d h:mm:s'){
        return y+'-'+timeAdd0(m)+'-'+timeAdd0(d)+' '+timeAdd0(h)+':'+timeAdd0(mm)+':'+timeAdd0(s);
    }else if(form == 'y-m-d'){
        return y+'-'+timeAdd0(m)+'-'+timeAdd0(d);
    }else if(form == 'h:mm:s'){
        return timeAdd0(h)+':'+timeAdd0(mm)+':'+timeAdd0(s);
    }else if(form == 'h:mm'){
        return timeAdd0(h)+':'+timeAdd0(mm);
    }else if(form == 'ymd h:mm:s'){
        return y+''+timeAdd0(m)+''+timeAdd0(d)+' '+timeAdd0(h)+':'+timeAdd0(mm)+':'+timeAdd0(s);
    }
}

export function getTimeNum(str){
    let date = new Date(str);
    return date.getTime()/1000;
}

// 数据映射成中文，只映射键
/**
 * @description 把JSON数据里的字段名做一个中文映射
 * @param {Array, Object} table 源JSON数组列表数据，可以为对象形式
 * @param {Object} thead JSON数组里的单个数据对象对应的英文对应的中文设置
 * @return {Array} 返回一个新的table数组 
 */
export function arrayMappingKeys(table, thead) {
    // Object.prototype.toString.call(table) === '[object Object]'
    // Object.prototype.toString.call(table) === '[object Array]'
    if(Array.isArray(table)){
        return table.map(item => {
            let obj = {};
            for (let prop in item) {
                if (thead.hasOwnProperty(prop)) {
                    obj[thead[prop]] = item[prop];
                }
            }
            return obj
        })
    }else{
        let obj = {};
        for (let prop in table) {
            if (thead.hasOwnProperty(prop)) {
                obj[thead[prop]] = item[prop];
            }
        }
        return obj;
    }
}

